package com.tc.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tc.domain.Disease_diagnosis;
import com.tc.domain.Insured_person;
import com.tc.domain.Patient_disease;
import com.tc.dto.Patient_diseaseDTO;
import com.tc.dto.Patient_diseaseQueryDTO;
import com.tc.mapper.Disease_diagnosisMapper;
import com.tc.mapper.Insured_personMapper;
import com.tc.mapper.Patient_diseaseMapper;
import com.tc.service.IPatient_diseaseService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tc.vo.PageResultVO;
import com.tc.vo.Patient_diseaseVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 患者疾病关联表 服务实现类
 * </p>
 *
 * @author tc
 * @since 2025-07-11
 */
@Service
public class Patient_diseaseServiceImpl extends ServiceImpl<Patient_diseaseMapper, Patient_disease> implements IPatient_diseaseService {

    @Autowired
    private Disease_diagnosisMapper diseaseDiagnosisMapper;
    
    @Autowired
    private Insured_personMapper insuredPersonMapper;

    @Override
    public PageResultVO<Patient_diseaseVO> pageQuery(Patient_diseaseQueryDTO queryDTO) {
        // 构建查询条件
        LambdaQueryWrapper<Patient_disease> queryWrapper = new LambdaQueryWrapper<>();
        
        // 添加查询条件
        if (queryDTO.getPatientId() != null) {
            queryWrapper.eq(Patient_disease::getPatientId, queryDTO.getPatientId());
        }
        
        if (queryDTO.getDiseaseId() != null) {
            queryWrapper.eq(Patient_disease::getDiseaseId, queryDTO.getDiseaseId());
        }
        
        if (queryDTO.getIsPrimary() != null) {
            queryWrapper.eq(Patient_disease::getIsPrimary, queryDTO.getIsPrimary());
        }
        
        // 按创建时间降序排序
        queryWrapper.orderByDesc(Patient_disease::getCreateTime);
        
        // 执行分页查询
        Page<Patient_disease> page = new Page<>(queryDTO.getPageNum(), queryDTO.getPageSize());
        Page<Patient_disease> resultPage = this.page(page, queryWrapper);
        
        // 获取疾病名称和患者姓名
        List<Patient_diseaseVO> records = convertToVOList(resultPage.getRecords());
        
        // 使用PageResultVO的静态方法直接构建分页结果对象
        return PageResultVO.convert(resultPage, records);
    }

    @Override
    public List<Patient_diseaseVO> getByPatientId(Long patientId) {
        LambdaQueryWrapper<Patient_disease> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Patient_disease::getPatientId, patientId);
        queryWrapper.orderByDesc(Patient_disease::getCreateTime);
        
        List<Patient_disease> list = this.list(queryWrapper);
        return convertToVOList(list);
    }

    @Override
    public Patient_diseaseVO getPatientDiseaseById(Long id) {
        Patient_disease patientDisease = this.getById(id);
        if (patientDisease == null) {
            return null;
        }
        
        Patient_diseaseVO vo = new Patient_diseaseVO();
        BeanUtils.copyProperties(patientDisease, vo);
        
        // 获取疾病信息
        Disease_diagnosis disease = diseaseDiagnosisMapper.selectById(patientDisease.getDiseaseId());
        if (disease != null) {
            vo.setDiseaseCode(disease.getDiseaseCode());
            vo.setDiseaseName(disease.getDiseaseName());
        }
        
        // 获取患者信息
        Insured_person patient = insuredPersonMapper.selectById(patientDisease.getPatientId());
        if (patient != null) {
            vo.setPatientName(patient.getName());
        }
        
        return vo;
    }

    @Override
    @Transactional
    public boolean addPatientDisease(Patient_diseaseDTO patientDiseaseDTO) {
        Patient_disease patientDisease = new Patient_disease();
        BeanUtils.copyProperties(patientDiseaseDTO, patientDisease);
        
        // 设置创建和更新时间
        LocalDateTime now = LocalDateTime.now();
        patientDisease.setCreateTime(now);
        patientDisease.setUpdateTime(now);
        patientDisease.setDeleted(0); // 设置为未删除
        
        // 如果诊断时间为空，则使用当前时间
        if (patientDisease.getDiagnosisTime() == null) {
            patientDisease.setDiagnosisTime(now);
        }
        
        // 如果是主诊断，则将该患者其他诊断设为非主诊断
        if (patientDisease.getIsPrimary() != null && patientDisease.getIsPrimary() == 1) {
            updatePrimaryDiagnosis(patientDisease.getPatientId());
        }
        
        return this.save(patientDisease);
    }

    @Override
    @Transactional
    public boolean updatePatientDisease(Patient_diseaseDTO patientDiseaseDTO) {
        Patient_disease patientDisease = new Patient_disease();
        BeanUtils.copyProperties(patientDiseaseDTO, patientDisease);
        
        // 设置更新时间
        patientDisease.setUpdateTime(LocalDateTime.now());
        
        // 如果是主诊断，则将该患者其他诊断设为非主诊断
        if (patientDisease.getIsPrimary() != null && patientDisease.getIsPrimary() == 1) {
            updatePrimaryDiagnosis(patientDisease.getPatientId());
        }
        
        return this.updateById(patientDisease);
    }

    @Override
    @Transactional
    public boolean deletePatientDisease(Long id) {
        return this.removeById(id);
    }
    
    /**
     * 将实体对象列表转换为视图对象列表
     * @param list 实体对象列表
     * @return 视图对象列表
     */
    private List<Patient_diseaseVO> convertToVOList(List<Patient_disease> list) {
        if (list == null || list.isEmpty()) {
            return new ArrayList<>();
        }
        
        // 获取所有疾病ID
        List<Integer> diseaseIds = list.stream()
                .map(Patient_disease::getDiseaseId)
                .distinct()
                .collect(Collectors.toList());
        
        // 获取所有患者ID
        List<Long> patientIds = list.stream()
                .map(Patient_disease::getPatientId)
                .distinct()
                .collect(Collectors.toList());
        
        // 批量查询疾病信息
        LambdaQueryWrapper<Disease_diagnosis> diseaseQueryWrapper = new LambdaQueryWrapper<>();
        diseaseQueryWrapper.in(Disease_diagnosis::getId, diseaseIds);
        List<Disease_diagnosis> diseases = diseaseDiagnosisMapper.selectList(diseaseQueryWrapper);
        Map<Integer, Disease_diagnosis> diseaseMap = diseases.stream()
                .collect(Collectors.toMap(Disease_diagnosis::getId, disease -> disease));
        
        // 批量查询患者信息
        LambdaQueryWrapper<Insured_person> patientQueryWrapper = new LambdaQueryWrapper<>();
        patientQueryWrapper.in(Insured_person::getPatientId, patientIds);
        List<Insured_person> patients = insuredPersonMapper.selectList(patientQueryWrapper);
        Map<Long, Insured_person> patientMap = patients.stream()
                .collect(Collectors.toMap(Insured_person::getPatientId, patient -> patient));
        
        // 转换为VO列表
        return list.stream().map(entity -> {
            Patient_diseaseVO vo = new Patient_diseaseVO();
            BeanUtils.copyProperties(entity, vo);
            
            // 设置疾病信息
            Disease_diagnosis disease = diseaseMap.get(entity.getDiseaseId());
            if (disease != null) {
                vo.setDiseaseCode(disease.getDiseaseCode());
                vo.setDiseaseName(disease.getDiseaseName());
            }
            
            // 设置患者信息
            Insured_person patient = patientMap.get(entity.getPatientId());
            if (patient != null) {
                vo.setPatientName(patient.getName());
            }
            
            return vo;
        }).collect(Collectors.toList());
    }
    
    /**
     * 更新主诊断
     * 将患者的其他诊断设为非主诊断
     * @param patientId 患者ID
     */
    private void updatePrimaryDiagnosis(Long patientId) {
        LambdaQueryWrapper<Patient_disease> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Patient_disease::getPatientId, patientId);
        queryWrapper.eq(Patient_disease::getIsPrimary, 1);
        
        List<Patient_disease> primaryDiagnoses = this.list(queryWrapper);
        if (!primaryDiagnoses.isEmpty()) {
            for (Patient_disease diagnosis : primaryDiagnoses) {
                diagnosis.setIsPrimary(0);
                diagnosis.setUpdateTime(LocalDateTime.now());
            }
            this.updateBatchById(primaryDiagnoses);
        }
    }
}
